#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<string>
#include<thread>
#include"inetaddr.hpp"

int sockfd =  -1;

void  Send(const std::string& ip,uint16_t port)
{
    InetAddr server(ip,port);
    std::string online = "online";
    sendto(sockfd,online.c_str(),online.size(),0,(struct sockaddr*)&server.GetAddr(),sizeof(server.GetAddr()));
    while(true)
    {
        std::string input;
        std::cout << "please input:";
        getline(std::cin,input);
        sendto(sockfd,input.c_str(),input.size(),0,(struct sockaddr*)&server.GetAddr(),sizeof(server.GetAddr()));
    }
}
 
void Recv()
{
    char buffer[1024];
    struct sockaddr_in server;
    socklen_t len  = sizeof(server); 
    while(true)
    {
        int n = recvfrom(sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&server,&len);
        buffer[n] = 0;
        std::cout << "接受到了一条消息:" << buffer <<std::endl;
    }
}


int main(int argc,char** argv)
{
    if(argc != 3)
    {   
        std::cerr << "usage:" << argv[0] << " serverip serverport"<<std::endl;
        exit(1);
    }
    sockfd =  socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd == -1)
    {
        std::cerr << "socket error" <<std::endl;
        exit(2);
    }
    std::thread send(Send,argv[1],std::stoi(argv[2]));
    std::thread recv(Recv);

    send.join();
    recv.join();
    
    return 0;
}